package yz.cp.back.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yz.cp.back.auth.security.SecurityUtils;
import yz.cp.back.common.base.BaseController;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.common.utils.PageKit;
import yz.cp.back.u.entity.UserRole;
import yz.cp.back.u.service.IUserRoleService;
import yz.cp.back.user.service.UserRoleMange;
import yz.cp.back.user.vo.UserRoleAuditVO;
import yz.cp.back.user.vo.UserRoleQueryVo;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/web/userRole")
public class UserRoleController extends BaseController {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private UserRoleMange userRoleMange;

    @PostMapping("getByCondition")
    public ApiResult getByCondition(UserRoleQueryVo vo) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>()
                .like(StringUtils.isNotBlank(vo.getMerchantName()), "merchant_name", vo.getMerchantName())
                .like(StringUtils.isNotBlank(vo.getLegalName()), "legal_name", vo.getLegalName())
                .like(StringUtils.isNotBlank(vo.getContactPhone()), "contact_phone", vo.getContactPhone())
                .eq(StringUtils.isNotBlank(vo.getAccessId()), "access_id", vo.getAccessId())
                .eq(vo.getRoleType() != null, "role_type", vo.getRoleType())
                .eq(vo.getStatus() != null, "status", vo.getStatus());
        if (vo.getStartDate() != null && vo.getEndDate() != null) {
            wrapper.between("ctime", vo.getStartDate().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond(), vo.getEndDate().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
        } else if (vo.getStartDate() != null) {
            wrapper.gt("ctime", vo.getStartDate().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
        } else if (vo.getEndDate() != null) {
            wrapper.lt("ctime", vo.getEndDate().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
        }
        IPage<UserRole> page = userRoleService.page(PageKit.buildPage(vo), wrapper);
        userRoleMange.getAccessUserRole(page.getRecords());
        return renderOk().add(page);
    }

    @PostMapping("getAccessList")
    public ApiResult getAccessList() {
        List<Map> list = Lists.newArrayList();
        List<UserRole> userRoleList = userRoleService.list(new QueryWrapper<UserRole>().lambda().eq(UserRole::getRoleType, 6));
        userRoleList.forEach(v -> {
            Map map = Maps.newHashMap();
            map.put("id", v.getId());
            map.put("merchantName", v.getMerchantName());
            list.add(map);
        });
        return renderOk().add(list);
    }


    @RequestMapping(value = "/disable/{id}", method = RequestMethod.POST)
    public ApiResult disable(@PathVariable String id) {
        UserRole userRole = new UserRole();
        userRole.setId(id);
        userRole.setStatus(3);
        userRoleService.updateById(userRole);
        return renderOk("操作成功");
    }

    @RequestMapping(value = "/enable/{id}", method = RequestMethod.POST)
    public ApiResult enable(@PathVariable String id) {
        UserRole userRole = new UserRole();
        userRole.setId(id);
        userRole.setStatus(1);
        userRoleService.updateById(userRole);
        return renderOk("操作成功");
    }


    @RequestMapping(value = "/detail/{id}", method = RequestMethod.POST)
    public ApiResult detail(@PathVariable String id) {
        UserRole userRole = userRoleService.getById(id);
        userRole.initNme();
        if (StringUtils.isNotBlank(userRole.getAccessId())) {
            UserRole access = userRoleService.getById(userRole.getAccessId());
            userRole.setAccessName(access.getMerchantName());
        } else {
            userRole.setAccessName("N/A");
        }

        return renderOk().add(userRole);
    }

    @RequestMapping(value = "audit", method = RequestMethod.POST)
    public ApiResult audit(@Valid UserRoleAuditVO vo) {
        UserRole userRole = userRoleService.getById(vo.getId());
        if (userRole == null) {
            return renderError("记录不存在");
        }
        if (vo.getStatus() != null && vo.getStatus() == 1) {
            //审核通过
            if (StringUtils.isBlank(vo.getMerchantAbbrName())) {
                return renderError("商户简称·必填");
            }
            if (userRoleService.count(new QueryWrapper<UserRole>().lambda().eq(UserRole::getAccessId, userRole.getAccessId())
                    .eq(UserRole::getMerchantAbbrName, vo.getMerchantAbbrName())) > 0) {
                return renderError("商户简称·重复");
            }
        }
        UserRole userRole1 = beanMapper.map(vo, UserRole.class);
        userRole1.setRtime(Long.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond()).intValue());
        userRole1.setRby(SecurityUtils.getSecUser().getUsername());
        userRoleService.updateById(userRole1);
        return renderOk();

    }


}
